package com.pp.small.common.utils;

import com.pp.small.common.constants.SecurityConstants;
import com.pp.small.common.constants.TokenConstants;
import com.pp.small.common.context.UserContext;

import javax.servlet.http.HttpServletRequest;

/**
 * 权限获取工具类
 *
 * @author ruoyi
 */
public class SecurityUtils {
    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        return UserContext.getUserId();
    }

    /**
     * 获取用户名称
     */
    public static String getUserName() {
        return UserContext.getUserName();
    }

    /**
     * 获取用户key
     */
    public static String getUserKey() {
        return UserContext.getUserKey();
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken(HttpServletRequest request) {
        // 从header获取token标识
        String token = request.getHeader(SecurityConstants.AUTHORIZATION);
        return replaceTokenPrefix(token);
    }

    private static String replaceTokenPrefix(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, "");
        }
        return token;
    }

}
